<template>
  <div class="editor-wrapper">
    <header class="header-wrapper">
      <input type="text" @input="changeSaveLocalFn" class="title-input" v-model="title" placeholder="请输入文章标题...">
      <div class="right-wrapper">
        <div class="status"><span v-show="status.show">{{status.text}}</span></div>
        <dl>
          <dt @click.stop="tagToggleFn">发布 <i class="iconfont " :class="tag.show ? 'icon-shangjiantou' : 'icon-xiajiantou'"></i></dt>
          <dd @click.stop v-show="tag.show">
            <div class="title">选择标签</div>
            <div class="tags">
              <Button v-for="v in tag.list" :key="v._id" @click="activeTagFn(v)" :class="{'active' : tag.active.includes(v._id)}">{{v.name}}</Button>
            </div>
            <div class="text">
              <input type="text" @keyup.enter="addTagFn" v-model="tag.value" placeholder="请输入标签名称">
              <div class="tishi">按下回车键，添加标签</div>
            </div>
            <Button v-if="!edit.id" class="submit" @click="addArticleFn">确认并发布</Button>
            <Button v-else class="submit" @click="editArticleFn">确认并修改</Button>
          </dd>
        </dl>
      </div>
    </header>
    <main class="editor-main" @dragenter="dropShade = true">
      <mavon-editor ref="editor" v-model="content" @change="changeSaveLocalFn" @save="saveLocalFn" fontSize="16px" :toolbars="toolbars" :toolbarsFlag="toolbarsFlag" />
      <div class="drop-shade" :class="dropShadeLoading ? 'loading' : ''" v-show="dropShade" @dragenter="dropShade = true" @drop.prevent="dropFn" @drag="dropShade = true" @dragleave="dropShade = false">
        <input type="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
      </div>
    </main>
  </div>
</template>
<script>

export default {
  name: 'editor',
  data () {
    return {
      num: 0,
      codeStyle: 'obsidian', // 主题样式
      toolbarsFlag: false,
      toolbars: {
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        link: true, // 链接
        imagelink: true, // 图片链接
        table: true, // 表格
        help: true, // 帮助
        save: false, // 保存
        fullscreen: false, // 全屏编辑
        readmodel: false, // 沉浸式阅读
        subfield: false, // 单双栏模式
        preview: false, // 预览
        navigation: true // 导航目录
      },
      title: '',
      content: '',
      tag: {
        list: [],
        active: [],
        value: '',
        show: false,
        default: ''
      },
      dropShade: false,
      dropShadeLoading: false,
      edit: {
        id: ''
      },
      status: {
        show: false,
        text: '已保存',
        timer: setTimeout(() => {}, 1500)
      },
      changeTimer: setTimeout(() => {}, 2000)
    }
  },
  components: {
  },
  watch: {},
  created () {
    if (!this.$route.query.id) {
      const data = this.$utils.store.get('editor')
      if (!this.title && !this.content) {
        this.title = data.title
        this.content = data.content
      }
    }
    this.getTagsListFn()
    this.getArticleInfoFn()
  },
  mounted () {
    this.$nextTick(() => {
      window.addEventListener('click', () => {
        this.tag.show = false
      })
    })
  },
  methods: {
    // 拖放后
    async dropFn (e) {
      const file = e.dataTransfer.files[0]
      try {
        await this.uploadImg(file)
        this.dropShadeLoading = false
      } catch (e) {
        console.log(e)
      }
      this.dropShade = false
    },
    async uploadImg (file = false) {
      if (file) {
        this.dropShadeLoading = true
        let form = new FormData()
        form.append('file', file)
        let {data} = await this.$http.post('/v1/articleUpload', form)
        this.mdAddImgUrl(file.name, data.url)
      }
    },
    tagToggleFn () {
      this.tag.show = !this.tag.show
    },
    // 是否选中未分类的函数
    isTagDefaultFn () {
      const tag = this.tag
      const list = tag.list
      let active = tag.active
      const len = active.length
      for (let i of list) {
        if (i.name === '未分类' && active.length === 0) {
          tag.default = i._id
        }
      }
      if (len === 0) {
        active.push(tag.default)
      } else {
        let ind = active.indexOf(tag.default)
        if (ind !== -1) {
          active.splice(ind, 1)
        }
      }
    },
    // 获取标签列表
    async getTagsListFn () {
      const {data} = await this.$http.get('/v1/tag')
      this.tag.list.push(...data.list)
      this.isTagDefaultFn()
    },
    // 选择标签
    activeTagFn (item) {
      const id = item._id
      const active = this.tag.active
      const index = active.indexOf(id)
      if (index < 0) {
        active.push(id)
      } else {
        active.splice(index, 1)
      }
      this.isTagDefaultFn()
    },
    // 发布/修改文章
    async addArticleFn (isedit = false) {
      const value = this.tag.value.trim()
      // 判断是否有需要添加的标签
      if (value) {
        if (!await this.addTagFn()) {
          return false
        }
      }
      let req = {
        title: this.title.trim(),
        content: this.content.trim(),
        tags: this.tag.active
      }
      let method = 'post'
      let ct = '发布'
      if (isedit) {
        req.id = this.edit.id
        method = 'put'
        ct = '修改'
      }
      if (!req.title) {
        console.log('老哥，没写题目')
        return false
      }
      if (!req.content) {
        console.log('老哥，没写内容')
        return false
      }
      try {
        const {data} = await this.$http[method]('/v1/article', req)
        this.$pop.confirm({
          content: '文章' + ct + '成功，点击确定查看文章',
          ok: () => {
            this.$router.push('/article/' + data.id)
          },
          cancel: () => {
            if (this.edit.id) {
              this.title = ''
              this.content = ''
              this.tag.active = []
              this.isTagDefaultFn()
            }
          }
        })
      } catch (e) {
        this.$pop.notice({
          title: '文章发布失败',
          type: 'error'
        })
      }
    },
    // 添加标签
    async addTagFn () {
      const req = {
        name: this.tag.value
      }
      try {
        const {data} = await this.$http.post('/v1/tag', req)
        this.tag.list.push({
          _id: data.id,
          name: this.tag.value
        })
        this.tag.active.push(data.id)
        this.isTagDefaultFn()
        this.tag.value = ''
        return true
      } catch (e) {
        return false
      }
    },
    // 编辑器中添加图片
    mdAddImgUrl (name, url) {
      name = name.replace(/\[|\]|\(|\)/g, '')
      if (name) {
        name = '未知名称'
      }
      this.$refs.editor.toolbar_left_addlink('img', name, url)
    },
    // 关于编辑的方法
    // 获取文章信息，并写入
    async getArticleInfoFn () {
      const id = this.$route.query.id
      if (!id) {
        return false
      }
      this.edit.id = id
      const params = {id}
      try {
        const {data} = await this.$http.get('/v1/article', {params})
        this.title = data.title
        this.content = data.content
        const tags = data.tags
        for (let i of tags) {
          this.tag.active.push(i._id)
        }
        this.isTagDefaultFn()
      } catch (e) {
        this.$pop.notice({
          title: '获取失败',
          type: 'error'
        })
      }
    },
    editArticleFn () {
      this.addArticleFn(true)
    },
    saveLocalFn () {
      const title = this.title
      const content = this.content
      if (!title && !content) {
        return false
      }
      this.status.show = true
      this.status.text = '保存中'
      clearTimeout(this.status.timer)
      this.$utils.store.set('editor', {title, content})
      this.status.text = '已保存'
      this.status.timer = setTimeout(() => {
        this.status.show = false
      }, 1500)
    },
    changeSaveLocalFn (code, html) {
      clearTimeout(this.changeTimer)
      this.changeTimer = setTimeout(() => {
        this.saveLocalFn()
      }, 2000)
    }
  }
}
</script>
